package com.calm.editor.handler;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public abstract class BaseService<T> {
	private EntityManager manager;
	protected static interface Query<T>{
		void query(CriteriaBuilder builder,CriteriaQuery<T> query,Root<T> from);
	}
	public T getById(Serializable id) {
		return manager.find(getEntityClass(), id);
	}

	public void update(T t) {
		manager.merge(t);
	}
	
	public List<T> query(Query<T> q){
		CriteriaBuilder builder = manager.getCriteriaBuilder();
		CriteriaQuery<T> query = builder.createQuery(getEntityClass());
		Root<T> from = query.from(getEntityClass());
		if(q!=null){
			q.query(builder, query, from);
		}
		TypedQuery<T> createQuery = manager.createQuery(query);
		return createQuery.getResultList();
	}
	
	public abstract Class<T> getEntityClass();

	@PersistenceContext 
	public void setManager(EntityManager manager) {
		this.manager = manager;
	}

}
